package zjut.raymond.witdemo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.lifecycle.ViewModelProvider;

import com.alibaba.fastjson.JSON;

import java.util.Date;
import java.util.List;
import java.util.Map;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.OkHttpFinal;
import cn.finalteam.okhttpfinal.RequestParams;
import zjut.raymond.witdemo.R;
import zjut.raymond.witdemo.pojo.ReferencePoint;
import zjut.raymond.witdemo.util.ApiResult;
import zjut.raymond.witdemo.util.CommonUtils;
import zjut.raymond.witdemo.viewmodel.CollectorViewModel;

public class AddRPDialog extends DialogFragment implements View.OnClickListener {
    public static final String TAG = "AddRPDialog";
    private CollectorViewModel collectorViewModel;
    private EditText editTextCoordX, editTextCoordY;
    private Button btnCancel, buttonOK;
    private Handler handler;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().setCancelable(false);
        getDialog().setCanceledOnTouchOutside(false);
        return inflater.inflate(R.layout.dialog_fragment_add_rp, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        collectorViewModel = new ViewModelProvider(getActivity()).get(CollectorViewModel.class);
        editTextCoordX = getView().findViewById(R.id.editTextRpCoordx);
        editTextCoordY = getView().findViewById(R.id.editTextRpCoordY);
        Spinner spinner = getView().findViewById(R.id.regionSpinner);
        btnCancel = getView().findViewById(R.id.btn_cancel);
        buttonOK = getView().findViewById(R.id.btn_ok);
        btnCancel.setOnClickListener(this);
        buttonOK.setOnClickListener(this);
        handler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case 0x01: {
                        new Thread(() -> HttpRequest.get("http://47.101.186.100:9102/collector/getRps", new BaseHttpRequestCallback<ApiResult>() {
                            @Override
                            protected void onSuccess(ApiResult apiResult) {
                                if (apiResult.getCode() == 200) {
                                    List<Map<String, Object>> rpLists = (List<Map<String, Object>>) apiResult.getData();
                                    for (Map<String, Object> rpMap : rpLists) {
                                        ReferencePoint referencePoint = JSON.parseObject(JSON.toJSONString(rpMap), ReferencePoint.class);
                                        collectorViewModel.addReferencePoint(referencePoint);
                                        Log.d(TAG, "onSuccess: " + JSON.toJSONString(referencePoint));
                                    }
                                }
                            }
                        })).start();
                        getDialog().dismiss();
                    }
                    break;
                    default:
                        super.handleMessage(msg);
                        break;
                }
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_cancel: {
                getDialog().dismiss();
            }
            break;
            case R.id.btn_ok: {
                String stringX = editTextCoordX.getText().toString();
                String stringY = editTextCoordY.getText().toString();
                if (CommonUtils.isNumeric(stringX) && CommonUtils.isNumeric(stringY)) {
                    Integer x = Integer.valueOf(stringX);
                    Integer y = Integer.valueOf(stringY);
                    ReferencePoint referencePoint = new ReferencePoint();
                    referencePoint.setX(x);
                    referencePoint.setY(y);
                    referencePoint.setUpdateTime(new Date());
                    referencePoint.setRegionId(1);
                    String jsonString = JSON.toJSONString(referencePoint);
                    RequestParams requestParams = new RequestParams();
                    requestParams.addFormDataPart("referencePointJson", jsonString);
                    new Thread(() -> HttpRequest.post("http://47.101.186.100:9102/collector/addRP", requestParams, new BaseHttpRequestCallback<ApiResult>() {
                        @Override
                        protected void onSuccess(ApiResult apiResult) {
                            switch (apiResult.getCode()) {
                                case 200: {
                                    Toast.makeText(getContext(), "添加成功", Toast.LENGTH_SHORT).show();
                                    handler.sendEmptyMessage(0x01);
                                }
                                break;
                                case 500: {
                                    Toast.makeText(getContext(), "添加失败", Toast.LENGTH_SHORT).show();
                                }
                                break;
                                default:
                                    break;
                            }
                        }
                        @Override
                        public void onFailure(int errorCode, String msg) {
                            super.onFailure(errorCode, msg);
                            Toast.makeText(getContext(), "添加失败", Toast.LENGTH_SHORT).show();
                        }
                    })).start();
                } else {
                    Log.d(TAG, "onClick: 输入有问题");
                }
            }
            break;
            default:
                break;
        }
    }
}
